package cn.lanqiao.web.controller;

import cn.lanqiao.common.entity.User;
import cn.lanqiao.common.utile.Result;
import cn.lanqiao.system.service.UserService;
import cn.lanqiao.web.utils.JwtUtils;
import cn.lanqiao.web.utils.RedisUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.naming.spi.DirStateFactory;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService ;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${redis.keys.login-tokens}")
    private String loginToken ;

    @Value("${redis.keys.login-times}")
    private String loginTimes ;

    @Value("${redis.expire-time.token-expire_time}")
    private Long expireTime ;

    /*    @RequestMapping("/findAllUser")
        @ResponseBody
        public Result findAllUser() {
            List<User> list = userService.findAllUser();
            if (list.size() > 0) {
                return Result.ok(list);
            } else {
                return Result.fail("系统错误");
            }
        }*/
    @RequestMapping("/getPage")
    @ResponseBody
    public Result getAll(@RequestParam(defaultValue = "1") int pageNO,
                         @RequestParam(defaultValue = "6") int pageSize){
        try{
            PageInfo<User> page =userService.getPage(pageNO,pageSize);
            return Result.ok(page);
        }catch (Exception e){
            e.printStackTrace();
        }

        return Result.fail("服务器出错!");
    }
    @GetMapping("/getTypePage")
    public Result getTypePage(@RequestParam(defaultValue = "1")  int pageNo,
                              @RequestParam(defaultValue = "6") int pageSize,Integer typeId){
        try{

            PageInfo<User> page=userService.getTypePage(pageNo,pageSize,typeId);
            return Result.ok(page);
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.fail("内部服务器出错");
    }
    @RequestMapping("/UserRegister")
    @ResponseBody
    public Result UserRegister(User user) {
        System.out.println("注册信息:"+user);
        List<User> list = userService.findUserByName(user.getUsername());
        if (list.size() > 0) {
            return Result.fail("用户名已存在,请重新注册");
        } else {
            Integer rs = userService.UserRegister(user);
            if (rs > 0) {

                return Result.ok("用户注册成功");
            } else {
                return Result.fail("用户注册失败");
            }
        }
    }
    @RequestMapping("/uploadImages")
    @ResponseBody
    public String uploadImages(MultipartFile file) throws IOException {
        if(file != null){

            //System.out.println("upload 的绝对路径 ： " + path);
            String path = "F:\\test3\\images\\";
            //判断一下 upload 文件夹是否存在
            File f = new File(path) ;
            if(!f.exists()){
                // 不存在，则创建
                f.mkdir() ;
            }

            //文件名
            String filename = file.getOriginalFilename() ;
            //获取文件后缀名
            String suffix = filename.substring(filename.lastIndexOf(".")) ;

            //重命名文件名，防止文件被覆盖
            // System.currentTimeMillis()
            String newFileName = UUID.randomUUID().toString().replaceAll("-","")+ suffix ;
            //上传的新文件
            File newFile = new File(path + "/" + newFileName);
            System.out.println("上传后的路径为 ：  " + path + "/" +newFileName);
            //把上传的file文件，保存在 upload 文件夹下（f）
            file.transferTo(newFile);

            //设置图书的图片路径
            return newFileName ; //返回图片的名称
        }

        return "" ;
    }
    @RequestMapping("/updateUser")
    //@ResponseBody
    public Result updateUser(User user) {
        System.out.println("收到的用户更改信息："+user);
        Integer  rs = userService.updateUserInfo(user);
        if(rs > 0) {
            return Result.ok("修改用户信息成功");
        }else {
            return Result.fail("系统错误");
        }
    }

    @RequestMapping("/deleteUser")
    @ResponseBody
    public Result deleteUser(Integer id) {

        Integer  rs = userService.deleteByPrimaryKey(id) ;
        if(rs > 0) {
            return Result.ok("删除成功");
        }else {
            return Result.fail("系统错误");
        }
    }
    @RequestMapping("/batchDeleteUser")//批量删除用户
    public Result batchDeleteUser(Integer[] ids){
        System.out.println("=============="+ids);
        try{

            int i=userService.batchDeleteUser(ids);
            if(i>0){
                return Result.ok();
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.fail("系统错误");
    }
    @RequestMapping("/save")
    @ResponseBody
    public Result save(User user){
        try{
            int r=userService.save(user);
            if(r>0){
                return Result.ok();
            }else{
                return Result.fail("保存失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.fail("系统异常");
    }


    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username, String password, String code, String uuid){
        System.out.println("数据："+username+"  "+password+"   " +code+"    "+uuid);

        try {

            if(!redisUtil.hasKey(uuid)){
                System.out.println("uuid："+redisUtil.hasKey(uuid));
                return Result.ok("验证码过期，请重新登录",4004);
            }

            String correctCode = String.valueOf(redisUtil.get(uuid));
            System.out.println("获取"+redisUtil.get(uuid));
            if(!correctCode.equals(code)){
                return Result.ok("验证码错误",4005);
            }

            User user = userService.login(username,password) ;
           // user.setUsername(username);
           // user.setPassword(password);
            if(user != null){//用户名密码正确
                //生成 token
                String token = JwtUtils.getJwtToken(user) ;
                System.out.println("user:"+user);
                System.out.println("token : " + token);
                //保存token到redis
                String key = loginToken + user.getUsername() ;
                redisUtil.set(key,token,expireTime) ;

                //返回给前端页面
                Result r = new Result();
                r.setCode(2000);
                r.setData(token);
                r.setUser(user);
                return r ;

            }else{
                //密码错误
                String key = loginTimes + user.getUsername() ;
                if(redisUtil.hasKey(key)){
                    int time = Integer.parseInt(redisUtil.get(key).toString()) ;
                    if((time + 1) == 3){
                        return Result.ok("您登录次数太频繁，请过一会再试",4005) ;
                    }
                    //获取之前的过期时间
                    long expire = redisUtil.getExpire(key) ;
                    redisUtil.del(key);
                    redisUtil.set(key,time+1,expire) ;
                }else{
                    redisUtil.set(key,1,60) ;
                }
                return Result.ok("用户名密码错误",4000) ;
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("系统异常");
        }

    }

    //产生验证码
    @RequestMapping("/getCode")
    public Result getCode(){
        //产生验证码
        String code = UUID.randomUUID().toString().replaceAll("-","").substring(0,4) ;



        //生成uuid
        String key = UUID.randomUUID().toString().replaceAll("-","").substring(0,6) ;

        //保存到redis
        redisUtil.set(key,code,60) ;
        Map map = new HashMap() ;
        map.put("key",key) ;
        map.put("code",code) ;
        return Result.ok(map) ;

    }

    @RequestMapping("/getUserById")
    public Result getUserById(Integer uid){
        System.out.println("getUserById(Integer uid)");
        if (uid == null){
            return Result.fail("id为null");
        }
        User user = userService.getUserById(uid);
        return Result.ok(user);
    }

    @RequestMapping("/updateUserById")
    public Result updateUserById(User user) {
        if (user.getId() == null) {
            return Result.fail();
        }
        int r = userService.updateUserById(user);
        if (r > 0){
            return Result.ok(user);
        }
        return Result.fail();
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            User user=userService.findById(id);
            if(user!=null){
                return Result.ok(user);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.fail("系统错误！");
    }

    //上传图片
    @RequestMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        if (file != null) {

            //System.out.println("upload 的绝对路径 ： " + path);
            String path = "E:/lanqiao/images";
            //判断一下 upload 文件夹是否存在
            File f = new File(path);
            if (!f.exists()) {
                // 不存在，则创建
                f.mkdir();
            }

            //文件名
            String filename = file.getOriginalFilename();
            //获取文件后缀名
            String suffix = filename.substring(filename.lastIndexOf("."));

            //重命名文件名，防止文件被覆盖
            // System.currentTimeMillis()
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            //上传的新文件
            File newFile = new File(path + "/" + newFileName);
            System.out.println("上传后的路径为 ：  " + path + "/" + newFileName);
            //把上传的file文件，保存在 upload 文件夹下（f）
            file.transferTo(newFile);

            //设置的图片路径
           // return newFileName; //返回图片的名称
            return Result.ok(newFileName);
        }

        return Result.ok();
    }

    //用户注册
    @RequestMapping("/userRegister")
    public Result userRegister(User user){
        System.out.println("---- userRegister ----");
        int r = userService.insertSelective(user);
        if (r > 0){
            System.out.println(user);
            return Result.ok();
        }
        return Result.fail("系统错误！");
    }
}
